package com.summer.data.connection.source;

import com.summer.data.connection.*;
import com.summer.data.connection.session.NormalSession;
import com.summer.data.connection.session.TransactionSession;
import com.summer.data.dialect.DatabaseProductID;
import com.summer.data.dialect.Dialect;
import com.summer.data.dialect.DialectCenter;
import com.summer.data.exception.SqlException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

/**
 * @author 345480567@qq.com
 */
public class DataSourceSessionFactory extends AbstractSessionFactory implements SessionFactory {

    private DataSource dataSource;

    public DataSourceSessionFactory(DataSource dataSource) {
        super(null);
        this.dataSource = dataSource;
        initDialect();
    }

    public DataSourceSessionFactory(DataSource dataSource, Dialect dialect) {
        super(dialect);
        this.dataSource = dataSource;
        initDialect();
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public Connection getConnection()  {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // todo:
//    public void beginTransaction(TransactionDef txDef, Callback1<Session> callback) {
//        SessionFactory dbSessionManager = SessionCenter.getDbSessionManager();
//        dbSessionManager.push(this);
//        beginTransaction(txDef);
//        checkInitOnUse();
//        try {
//            callback.apply(this);
//            commit();
//            conn.setAutoCommit(oldAutoCommit);
//        } catch (SQLException e) {
//            try {
//                rollback();
//            } catch (SQLException ex) {
//                throw new RuntimeException(ex);
//            }
//        } finally {
//            dbSessionManager.pop();
//        }
//    }

//    public void beginTransaction(TransactionDef txDef) {
//        this.txDef = txDef;
//    }


}
